package cc.z8g.browser.utils.sp

import android.annotation.SuppressLint
import android.app.Application
import cc.z8g.browser.BuildConfig
import cc.z8g.browser.core.BrowserConst
import cc.z8g.browser.search.BaiduSearch
import cc.z8g.browser.search.BaseSearchEngine
import cc.z8g.browser.search.BingSearch
import cc.z8g.browser.search.CustomSearch
import cc.z8g.browser.search.GoogleSearch
import cc.z8g.browser.search.suggestions.SearchConst
import cc.z8g.browser.search.suggestions.SearchEngineProvider
import cc.z8g.browser.utils.FileUtils

/**
 * 用户配置
 */
object UserSp {
    const val KEY_LEAK_CANARY = "leak_canary"

    const val KEY_WEB_RTC = "webRtc"
    /** 如果浏览器应该阻止加载图片，则为true，否则为false。 */
    const val KEY_BLOCK_IMAGES = "block_images"
    const val KEY_EXIT_CLEAR_CACHE = "exit_clear_cache"
    const val KEY_EXIT_CLEAR_HISTORY = "exit_clear_history"
    const val KEY_EXIT_CLEAR_COOKIES = "exit_clear_cookies"
    const val KEY_EXIT_CLEAR_WEB_STORAGE = "exit_clear_web_storage"

    /** 如果浏览器应允许网站存储和访问Cookies，则为true，否则为false */
    const val KEY_THIRD_PARTY_COOKIES = "third_party_cookies"
    const val KEY_DOWNLOAD_DIR = "downloadLocation"
    /** 如果在滚动时浏览器应隐藏导航栏，则为true；如果导航栏应固定不动，则为false。 */
    const val KEY_FULL_SCREEN = "fullscreen"

    const val KEY_START_PAGE = "start_page"
    const val START_PAGE_USE_BOOKMARKS = 0
    const val START_PAGE_USE_URL = 1
    const val START_PAGE_URL = "start_page_url"

    const val KEY_INCOGNITO_THIRD_PARTY_COOKIES = "incognito_third_party_cookies"
    /** 如果浏览器应允许执行 JavaScript，则为true；否则为false。 */
    const val KEY_JAVASCRIPT = "javascript"
    const val KEY_LOCATION = "location"
    /** 如果浏览器应以缩小页面的方式加载页面，以便文本可读，则为true；否则为false。 */
    const val KEY_OVERVIEW_MODE = "overview_mode"
    /** 如果浏览器应允许网站打开新窗口，则为true；否则为false。*/
    const val KEY_POPUPS = "popups"
    /** 如果应用程序应记住已打开的浏览器选项卡，并在浏览器被系统自动关闭时恢复它们，则为true。*/
    const val KEY_RESTORE_LOST_TABS = "restoreclosed"
    /** 如果在放大或缩小页面后浏览器应尝试重新排列页面上的文本，则为true；否则为false。 */
    const val KEY_TEXT_REFLOW = "text_reflow"
    /** 拿到这个值后，需要+100再使用，0表示默认缩放比，100% */
    const val KEY_TEXT_ZOOM = "text_zoom"
    const val KEY_USE_WIDE_VIEWPORT = "wideviewport"
    const val USER_AGENT = "agentchoose"
    const val USER_AGENT_STRING = "userAgentString"

    /** 如果浏览器应从网站提取主题颜色并将UI着色，则为true；否则为false。 */
    const val KEY_THEME_COLOR = "theme_color"
    const val KEY_BOX_DISPLAY = "box_display"
    const val BOX_DISPLAY_DOMAIN = 2
    const val BOX_DISPLAY_URL = 1
    const val BOX_DISPLAY_TITLE = 0

    /** 0亮色(默认值)，1暗色，2黑色 */
    const val KEY_THEME = "theme"
    const val THEME_BLACK = 0
    const val THEME_LIGHT = 2
    const val THEME_DARK = 1

    const val TEXT_ENCODING = "textEncoding"
    const val KEY_DO_NOT_TRACK = "do_not_track"
    const val KEY_SAVE_DATA = "save_data"
    const val KEY_REMOVE_IDENTIFYING_HEADERS = "remove_identifying_headers"
    /** 如果应用程序的状态栏应始终高对比度，则为true；否则根据应用程序主题。 */
    const val KEY_BLACK_STATUS_BAR = "black_status_bar"

    /** int 值选择搜索引擎类型 */
    const val KEY_SEARCH_ENGINE = "search_engine"
    /** 自定义搜索引擎的 url */
    const val KEY_SEARCH_ENGINE_CUSTOM_URL = "search_engine_custom_url"
    /** 搜索建议 */
    const val KEY_SEARCH_SUGGESTION = "search_suggestion"

    private val userSp = SpManager.getUserSp()

    @JvmStatic
    fun getBoolean(key: String): Boolean {
        val defTrue: Boolean = key == KEY_DO_NOT_TRACK || key == KEY_SAVE_DATA || key == KEY_WEB_RTC
                || key == KEY_THIRD_PARTY_COOKIES || key == KEY_FULL_SCREEN || key == KEY_JAVASCRIPT
                || key == KEY_OVERVIEW_MODE || key == KEY_POPUPS || key == KEY_RESTORE_LOST_TABS
                || key == KEY_USE_WIDE_VIEWPORT || key == KEY_THEME_COLOR
                || (BuildConfig.DEBUG && key == KEY_LEAK_CANARY)
        return userSp.getBoolean(key, defTrue);
    }

    /** 获取启动页 */
    fun getStartPage(): String {
        if (userSp.getInt(KEY_START_PAGE, START_PAGE_USE_BOOKMARKS) == START_PAGE_USE_BOOKMARKS) {
            return BrowserConst.SCHEME_BOOKMARKS
        } else {
            val customUrl = userSp.getString(START_PAGE_URL, "")
            return if (customUrl.isNullOrEmpty()) BrowserConst.SCHEME_BOOKMARKS else customUrl
        }
    }

    /** 搜索建议选择的索引。 [SearchEngineProvider] */
    @SearchConst.Suggestion
    fun getSearchSuggestion(): Int {
        return userSp.getInt(KEY_SEARCH_SUGGESTION, SearchConst.SUGGESTION_BAIDU)
    }

    /** 获取搜索引擎的queryUrl */
    fun getSearchEngine(): BaseSearchEngine {
        return when (userSp.getInt(KEY_SEARCH_ENGINE, SearchConst.ENGINE_BAIDU)) {
            SearchConst.ENGINE_BAIDU -> BaiduSearch()
            SearchConst.ENGINE_CUSTOM -> {
                var queryUrl = userSp.getString(KEY_SEARCH_ENGINE_CUSTOM_URL, "")
                if (queryUrl.isNullOrBlank()) {
                    queryUrl = BaiduSearch().queryUrl
                }
                CustomSearch(queryUrl)
            }

            SearchConst.ENGINE_GOOGLE -> GoogleSearch()
            SearchConst.ENGINE_BING -> BingSearch()
            else -> BaiduSearch()
        }
    }

    @JvmStatic
    fun getString(key: String): String {
        val value = userSp.getString(key, "")
        if (value.isNullOrBlank()) { // 设置默认值
            return when (key) {
                KEY_DOWNLOAD_DIR -> return FileUtils.getDefaultDownloadDir().absolutePath
                TEXT_ENCODING -> return BrowserConst.DEFAULT_ENCODING
                else -> ""
            }
        }
        return value
    }

    @JvmStatic
    fun getInt(key: String): Int {
        return userSp.getInt(key, 0);
    }

    @JvmStatic
    fun putInt(key: String, value: Int) {
        userSp.edit().putInt(key, value).apply();
    }

    @JvmStatic
    fun putBoolean(key: String, value: Boolean) {
        userSp.edit().putBoolean(key, value).apply()
    }

    @JvmStatic
    fun putString(key: String, value: String) {
        userSp.edit().putString(key, value).apply()
    }

    @JvmStatic
    var userAgentChoice = userSp.getInt(USER_AGENT, 1)

    /** 应由浏览器使用的自定义用户代理。 */
    @JvmStatic
    var userAgentString = userSp.getString(USER_AGENT_STRING, "")

    /**
     * Return the user agent chosen by the user or the custom user agent entered by the user.
     */
    @JvmStatic
    fun userAgent(application: Application): String = BrowserConst.MOBILE_USER_AGENT
//        when (val choice = userAgentChoice) {
//            1 -> WebSettings.getDefaultUserAgent(application)
//            2 -> BrowserConst.DESKTOP_USER_AGENT
//            3 -> BrowserConst.MOBILE_USER_AGENT
//            4 -> userAgentString.takeIf(String::isNotEmpty) ?: " "
//            else -> throw UnsupportedOperationException("Unknown userAgentChoice: $choice")
//        }

    @JvmStatic
    fun userAgent(defaultUserAgent: String): String = BrowserConst.MOBILE_USER_AGENT
//        when (val choice = userAgentChoice) {
//            1 -> defaultUserAgent
//            2 -> BrowserConst.DESKTOP_USER_AGENT
//            3 -> BrowserConst.MOBILE_USER_AGENT
//            4 -> userAgentString.takeIf(String::isNotEmpty) ?: " "
//            else -> throw UnsupportedOperationException("Unknown userAgentChoice: $choice")
//        }

    /** 同步清理所有设置  */
    @SuppressLint("ApplySharedPref")
    fun clearUserSp() {
        SpManager.getUserSp().edit().clear().commit()
    }
}

